
package org.scache.serialization.json;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;

import org.scache.serialization.ISerializer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * JSON 序列化实现，被序列化的对象需要符合JavaBean规范（私有成员提供setter和getter以及默认构造方法）
 * 
 * @author 君枫
 * @version 1.0
 * @since 2014-8-19 下午10:05:42
 * @category com.ailk.serialization.json
 */
public class JSONSerializer implements ISerializer
{

	static final String CHARSET = "UTF-8";

	@Override
	public byte[] serialize(Serializable s)
	{
		if (s != null)
		{
			return JSON.toJSONBytes(s, SerializerFeature.WriteClassName);
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T deserialize(byte[] bytes)
	{
		if (bytes != null)
		{
			try
			{
				return (T) JSON.parse(new String(bytes, CHARSET));
			}
			catch (UnsupportedEncodingException e)
			{
				log.error("反序列化对象失败:" + e.getMessage());
			}
		}
		return null;
	}

	static class Person implements Serializable
	{

		private static final long serialVersionUID = -8223444661936773687L;
		String name;
		int age;

		public String getName()
		{
			return name;
		}

		public void setName(String name)
		{
			this.name = name;
		}

		public int getAge()
		{
			return age;
		}

		public void setAge(int age)
		{
			this.age = age;
		}

		public Person(String name, int age)
		{
			super();
			this.name = name;
			this.age = age;
		}

		public Person()
		{
			super();
		}

		@Override
		public String toString()
		{
			return "Person [name=" + name + ", age=" + age + "]";
		}
	}

	public static void main(String[] args)
	{
		ISerializer jsonSerializer = new JSONSerializer();
		Person p = new Person("junfeng", 10);
		byte[] bs = jsonSerializer.serialize(p);
		p = jsonSerializer.deserialize(bs);
		System.out.println(p);
	}
}
